﻿using System;
using System.IO;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Easy.Model;
using Easy.Operation;
using Easy.Operation.Data;
using Yahoo.Yui.Compressor;
using System.Dynamic;

namespace Easy.BLL
{
    public class FormDataBLL
    {
        public string GetFormJson(HttpContext context, String FormSet, Guid id, SystemUserModel CurrentUser)
        {
            dynamic ReturnJson = new ExpandoObject();

            PageForm form = new PageForm(context, CurrentUser);
            var FormStructure = form.GetFormStructure(FormSet);
            if (FormStructure != null)
            {
                String FormHtml = FormStructure[0];
                String FormJs = new JsHubBLL().GetJsWithEntityItemName("form", context.Request["entityname"].ToLower(), FormSet);
                String JsBeforeLoadData = FormStructure[3];
                String JsAfterLoadData = FormStructure[4];
                String JsBeforeSaveData = FormStructure[5];
                String JsAfterSaveData = FormStructure[6];

                ReturnJson.FormHtml = FormHtml;
                ReturnJson.FormJs = FormJs;
                ReturnJson.JsBeforeLoadData = JsBeforeLoadData;
                ReturnJson.JsAfterLoadData = JsAfterLoadData;
                ReturnJson.JsBeforeSaveData = JsBeforeSaveData;
                ReturnJson.JsAfterSaveData = JsAfterSaveData;
            }

            if (id != Guid.Empty)
            {
                ReturnJson.data = form.EntityData;
            }
            else
            {
                ReturnJson.id = Guid.NewGuid().ToString();
            }

            ReturnJson.EntityField = form.Fields;
            ReturnJson.EntityOption = form.Options;
            ReturnJson.Privilege = form.UserPrivilege;
            ReturnJson.FunctionPrivilege = form.FunctionPrivilege;
            ReturnJson.Attachment = form.GetAttachments();
            return JsonConvert.SerializeObject(ReturnJson);

        }
    }
}